package com.zero.yygh.cmn.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zero.yygh.cmn.listener.DictExcelListener;
import com.zero.yygh.cmn.mapper.DictMapper;
import com.zero.yygh.cmn.service.DictService;
import com.zero.yygh.model.cmn.Dict;
import com.zero.yygh.vo.cmn.DictEeVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.security.krb5.internal.PAEncTSEnc;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zero
 * @desc 数据字典管理服务实现
 * @create 2021/3/14
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    /**
     * 根据id查询子节点数据
     * @author zero
     * @date 2021/3/24 10:59
     * @param id id
     * @return java.util.List<com.zero.yygh.model.cmn.Dict>
     * //@Cacheable 启用缓存功能
     */
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChildData (Long id) {
        // 查询条件构造器
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        //向list集合每个dict对象中设置hasChildren
        for (Dict dict:dictList) {
            Long dictId = dict.getId();
            boolean isChild = this.isChildren(dictId);
            dict.setHasChildren(isChild);
        }
        return dictList;

    }

    /**
     * 导出数据字典到excel
     * @param response res响应
     * @author zero
     * @date 2021/3/24 13:42
     */
    @Override
    public void exportDictData (HttpServletResponse response) {
        try {
            // 设置下载信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

            List<Dict> dictList = baseMapper.selectList(null);
            List<DictEeVo> dictVoList = new ArrayList<>(dictList.size());
            for(Dict dict : dictList) {
                DictEeVo dictVo = new DictEeVo();
                BeanUtil.copyProperties(dict, dictVo);
                dictVoList.add(dictVo);
            }

            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 上传文件
     * @param file 文件内容
     * @author zero
     * @date 2021/3/24 14:34
     * // @CacheEvict allEntries=true 清空该缓存
     */
    @Override
    @CacheEvict(value = "dict", allEntries=true)
    public void importDictData (MultipartFile file) {
        try {
            // 读取文件输入流，将数据转为 数据库内容实体，添加按行处理事件
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictExcelListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据上级编码与值获取数据字典名称
     * @param parentDictCode 上级编码
     * @param value          值
     * @return java.lang.String
     * @author zero
     * @date 2021/3/28 20:48
     */
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    @Override
    public String getNameByParentDictCodeAndValue (String parentDictCode, String value) {
        //如果value能唯一定位数据字典，parentDictCode可以传空，例如：省市区的value值能够唯一确定
        Dict dict = null;
        if (StringUtils.isEmpty(parentDictCode)) {
            dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("value", value));
        } else {
            Dict parentDict = this.getDictByDictCode(parentDictCode);
            if (null == parentDict) {
                return "";
            }
            dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("parent_id", parentDict.getId()).eq("value", value));
        }
        if (dict != null) {
            return dict.getName();
        }
        return "";
    }

    /**
     * 根据字典编号查询子列表
     * @param dictCode 字典编号
     * @return java.util.List<com.zero.yygh.model.cmn.Dict>
     * @author zero
     * @date 2021/3/29 11:02
     */
    @Override
    public List<Dict> findByDictCode (String dictCode) {
        Dict codeDict = this.getDictByDictCode(dictCode);
        if(null == codeDict) {
            return null;
        }
        return this.findChildData(codeDict.getId());
    }

    /**
     * 根据父级编号查询字典信息
     * @author zero
     * @date 2021/3/28 21:04
     * @param parentDictCode 父级字典编号
     * @return com.zero.yygh.model.cmn.Dict
     */
    private Dict getDictByDictCode (String parentDictCode) {
        return baseMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", parentDictCode));
    }

    /**
     * 判断是否是子节点
     * @author zero
     * @date 2021/3/24 11:03
     * @param id  id
     * @return boolean
     */
    private boolean isChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        // 大于 0 表示有子节点
        return count > 0;
    }

}
